﻿using IAMH.MVC.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;

namespace IAMH.MVC.Controllers
{
    /// <summary>
    /// httpClient请求封装
    /// </summary>
    public class HttpClientController : Controller
    {
        private readonly IHttpClientFactory _httpClient;
        private static string _token;

        public HttpClientController(IHttpClientFactory httpClientFactory)
        {
            _httpClient = httpClientFactory;
        }

        //private HttpClient CreateHttpClient()
        //{
        //    var token = localStorage.getItem("token");
        //    _httpClient.CreateClient().DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer ", token); // 设置 Token
        //}

        //[HttpPost]
        //public async Task<IActionResult> Post(string url, string parameters)
        //{
        //    // 创建 HttpClient 实例
        //    var httpClient = _httpClient.CreateClient();
        //    // 设置 Token
        //    //string token = "YourTokenHere"; // 替换成你的实际 Token
        //    // 将 Token 添加到请求头中
        //    //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer ", token);
        //    // 构建完整的URL，并添加参数
        //    // 发送 POST 请求
        //    HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, parameters);
        //    response.EnsureSuccessStatusCode(); // 确保响应成功
        //    string responseBody = await response.Content.ReadAsStringAsync();
        //    return Content(responseBody); // 返回获取的数据
        //}

        /// <summary>
        /// GET请求（无参数）
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task<IActionResult> Get(string url)
        {
            //string newUrl = $"https://api.example.com/data?input={url}"; // 构建完整的URL
            var httpClient = _httpClient.CreateClient();
            //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);
            HttpResponseMessage response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode(); // 确保响应成功
            string responseBody = await response.Content.ReadAsStringAsync();
            return Content(responseBody); // 返回获取的数据
        }

        /// <summary>
        /// GET请求（带参数）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetParam(string url, IDictionary<string, string> parameters)
        {
            // 创建 HttpClient 实例
            var httpClient = _httpClient.CreateClient();
            // 设置 Token
            //string token = "YourTokenHere";
            // 将 Token 添加到请求头中
            //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);
            // 构建完整的URL，并添加参数
            var requestUri = $"{url}?{DictionaryToString(parameters)}";
            // 发送 GET 请求
            HttpResponseMessage response = await httpClient.GetAsync(requestUri);
            response.EnsureSuccessStatusCode(); // 确保响应成功
            // 读取响应内容
            string responseBody = await response.Content.ReadAsStringAsync();
            return Content(responseBody); // 返回获取的数据
        }

        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login([FromBody] LoginInfo loginInfo)
        {
            // 创建 HttpClient 实例
            var httpClient = _httpClient.CreateClient();
            // 发送 POST 请求
            var json = JsonConvert.SerializeObject(loginInfo);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await httpClient.PostAsync("http://10.31.60.18:8000/AuthorizationPeopleGetRout/api/RegUserData/LoginDo", content);
            response.EnsureSuccessStatusCode(); // 确保响应成功
            // 读取响应内容
            string responseBody = await response.Content.ReadAsStringAsync();
            _token = JObject.Parse(responseBody)["token"].ToString();
            return Content(responseBody); // 返回获取的数据
        }

        /// <summary>
        /// 字典转字符串
        /// </summary>
        /// <param name="dictionary"></param>
        /// <returns></returns>
        public static string DictionaryToString(IDictionary<string, string> dictionary)
        {
            StringBuilder sb = new StringBuilder();

            // 遍历字典中的每个键值对
            foreach (var kvp in dictionary)
            {
                // 将键值对格式化为字符串，并追加到 StringBuilder
                sb.Append(kvp.Key);
                sb.Append("=");
                sb.Append(kvp.Value);
                sb.Append("&");
            }

            // 删除最后一个逗号和空格
            if (sb.Length > 0)
            {
                sb.Length -= 1;
            }

            // 返回最终的字符串形式
            return sb.ToString();
        }
    }
}